package com.cxx.home.service.impl;

import com.cxx.home.dto.message.MailMessageDto;
import com.cxx.home.service.MessageService;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public void sendMailMessage(MailMessageDto mailMessageDto) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom("njcxx0822@163.com");
            helper.setTo(mailMessageDto.getTo());
            helper.setSubject(mailMessageDto.getSubject());
            helper.setText(mailMessageDto.getBody(), true);

            // 发送邮件
            javaMailSender.send(mimeMessage);
            log.info("邮件发送成功");
        } catch (MessagingException e) {
            log.error("邮件发送失败: {}", e.getMessage());
        }
    }

    @Override
    public void sendWxMessage() {
        WxMpDefaultConfigImpl wxStorage = new WxMpDefaultConfigImpl();
        wxStorage.setAppId("wxdf137d1a34489880");
        wxStorage.setSecret("25b73681c66a480e726d67bb38aeb71e");

        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        // 此处的 key/value 需和模板消息对应
        List<WxMpTemplateData> wxMpTemplateDataList = List.of(
                new WxMpTemplateData("test", "Hello World")
        );

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser("ol1ZM7PJvNZ4MXWglwz68GtQCppI") // openId为1.3步骤中得到的微信号
                .templateId("JoY6-AmAxLLU7N-tG0-Bl2o0P3_j7gTI4O-L2nZ0R8g")
                .data(wxMpTemplateDataList)
                .build();

        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            log.info("推送消息成功");
        } catch (Exception e) {
            log.error("推送失败：{}", e.getMessage());
        }
    }
}
